﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace Talk.Net.Server
{
	class ContentManager
	{
		private static Queue<byte[]> content;
		private static object threadLock = new object();
		private static ReaderWriterLock rwl = new ReaderWriterLock();

		public delegate void ContentNotifierDelegate(byte[] content);
		public static event ContentNotifierDelegate ContentNotification;

		public static void AddContent(byte[] buffer)
		{
			rwl.AcquireWriterLock(Timeout.Infinite);
			Init();
			// this queue made sense, before, now, not so much...
			content.Enqueue(buffer);
			ContentNotification(content.Dequeue());
			rwl.ReleaseLock();
		}

		public static byte[] GetContent()
		{
			rwl.AcquireReaderLock(Timeout.Infinite);
			Init();
			byte[] work = content.Dequeue();
			rwl.ReleaseLock();

			return work;
		}

		public static int GetSize()
		{
			rwl.AcquireWriterLock(Timeout.Infinite);

			int total = 0;
			foreach (byte[] buffer in content)
			{
				total = total + buffer.Length;
			}
			rwl.ReleaseLock();
			return total;
		}

		private static void Init()
		{
			if (content == null)
			{
				content = new Queue<byte[]>();
			}
		}
	}
}
